package com.ybu.service.impl;

import com.ybu.common.ServiceCode;
import com.ybu.common.ServiceException;
import com.ybu.mapper.AddFavoriteMapper;
import com.ybu.mapper.ProductMapper;
import com.ybu.pojo.entity.Favorite;
import com.ybu.pojo.entity.Product;
import com.ybu.pojo.vo.UserLoginVO;
import com.ybu.service.AddFavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AddFavoriteServiceImpl implements AddFavoriteService {

    @Autowired
    private  AddFavoriteMapper addFavoriteMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public void addFavorite(Integer productId, UserLoginVO userLoginVO) {
        //判断这个上编号是否存在
        Product product = productMapper.getById(productId);
        if(product==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该商品不存在");
        }
        Favorite existingFavorite = addFavoriteMapper.findByProductIdAndUserId(productId, userLoginVO.getId());
        //根据商品编号和用户编号查询收藏，判断是否已经被收藏，如果已经收藏，告知前端，如果没收藏，那就新增
        if (existingFavorite != null) {
            throw new RuntimeException("商品已被收藏");
        } else {
            Favorite favorite = new Favorite();
            favorite.setUserId(userLoginVO.getId());
            favorite.setProductId(productId);
            favorite.setCreatedUser(userLoginVO.getUsername());
            addFavoriteMapper.insert01(favorite);
        }
    }
}
